<?php
/**
 * Author: Nguyen Hoai Tan (nguoiao007@gmail.com)
 * 
 * @category   default 
 * @copyright  Copyright (c) 2009 visualidea.org
 * @license    http://license.visualidea.org
 * @version    v 1.0 2009-04-15
 * 
 */
require_once 'modules/product/models/Product.php';
require_once 'modules/product/models/ProductCategory.php';
require_once 'modules/language/models/Lang.php';
class product_AdminController extends Nine_Controller_Action_Admin 
{
    
    public function manageProductAction()
    {
        $objProduct = new Models_Product();
        $objLang    = new Models_Lang();
        $objCat     = new Models_ProductCategory();
        
        /**
         * Check permission
         */
        if (false == $this->checkPermission('see_product', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $this->view->headTitle(Nine_Language::translate('manage Product '));
        $this->view->menu = array('product', 'manageproduct');
        
        
        $config = Nine_Registry::getConfig();
        $numRowPerPage = Nine_Registry::getConfig("defaultNumberRowPerPage");
        $currentPage = $this->_getParam("page",1);
        $displayNum = $this->_getParam('displayNum', false);
        
        /**
         * Update sorting
         */
        $data = $this->_getParam('data', array());
        foreach ($data as $id=>$value) {
            $value = intval($value);
            if (1 > $value) {
                continue;
            }
            $objProduct->update(array('sorting' => $value), array('product_gid=?' => $id));
            $this->session->productMessage = array(
                                       'success' => true,
                                       'message' => Nine_Language::translate("Product Order is edited successfully")
                                   );
        }
        
        /**
         * Get number of items per page
         */
        if (false === $displayNum) {
            $displayNum = $this->session->productDisplayNum;
        } else {
            $this->session->productDisplayNum = $displayNum;
        }
        if (null != $displayNum) {
            $numRowPerPage = $displayNum;
        }
        /**
         * Get condition
         */
        $condition = $this->_getParam('condition', false);
        if (false === $condition) {
            $condition = $this->session->productCondition;
        } else {
            $this->session->productCondition = $condition;
            $currentPage = 1;
        }
        if (false == $condition) {
            $condition = array();
        }
        
        /**
         * Get all categories
         */
        $this->view->allCats = $objCat->buildTree($objCat->getAll(array('sorting ASC'))->toArray());
        /**
         * Get all display languages
         */
        $allLangs = $objLang->getAll(array('sorting ASC'))->toArray();
        /**
         * Check permisison for each language
         */
        foreach ($allLangs as $index => $lang) {
            if (false == $this->checkPermission('see_product', null, $lang['lang_id'])) {
                /**
                 * Disappear this language
                 */
                unset($allLangs[$index]);
            }
        }
        
        /**
         * Get all products
         */
        
        $allProduct = $objProduct->setAllLanguages(true)->getAllProducts($condition, array('sorting ASC', 'product_gid DESC', 'product_id ASC'),
                                                   $numRowPerPage,
                                                   ($currentPage - 1) * $numRowPerPage
                                                  );
//        echo '<pre>';print_r($allProduct);die;
        /**
         * Count all products
         */
        $count = count($objProduct->setAllLanguages(true)->getAllProducts($condition));
        /**
         * Format
         */
        $tmp    = array();
        $tmp2   = false;
        $tmpGid = @$allProduct[0]['product_gid'];
        foreach ($allProduct as $index=>$product) {
            /**
             * Change date
             */
            if (0 != $product['created_date']) {
                $product['created_date'] = date($config['dateFormat'], $product['created_date']);
            } else {
                $product['created_date'] = '';
            }
            if (0 != $product['sale_off_start_date']) {
                $product['sale_off_start_date'] = date($config['dateFormat'], $product['sale_off_start_date']);
            } else {
                $product['sale_off_start_date'] = '';
            }
            if (0 != $product['sale_off_end_date']) {
                $product['sale_off_end_date'] = date($config['dateFormat'], $product['sale_off_end_date']);
            } else {
                $product['sale_off_end_date'] = '';
            }
            if ($tmpGid != $product['product_gid']) {
                $tmp[]  = $tmp2;
                $tmp2   = false;
                $tmpGid = $product['product_gid'];
            }
            if (false === $tmp2) {
                $tmp2        = $product;
                $tmp2['hit'] = 0;
            }
            $tmp2['hit']    += $product['hit'];
            $tmp2['langs'][]  = $product;
            /**
             * Final element
             */
            if ($index == count($allProduct) - 1) {
                $tmp[] = $tmp2;
            }
        }
        $allProduct = $tmp;
//        echo '<pre>';print_r($allProduct);die;
        /**
         * Set values for tempalte
         */
        $this->setPagination($numRowPerPage, $currentPage, $count);
        $this->view->allProduct = $allProduct;
        $this->view->productMessage = $this->session->productMessage;
        $this->session->productMessage = null;
        $this->view->condition = $condition;
        $this->view->displayNum = $numRowPerPage;
        $this->view->fullPermisison = $this->checkPermission('see_product');
        $this->view->allLangs = $allLangs;
    }
    
    public function newProductAction()
    {
        $objCat = new Models_ProductCategory();
        $objLang = new Models_Lang();
        $objProduct = new Models_Product();
        /**
         * Check permission
         */
        if (false == $this->checkPermission('new_product', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $data = $this->_getParam('data', false);
        /**
         * Get all categories
         */
        $allCats = $objCat->buildTree($objCat->getAll(array('sorting ASC'))->toArray());
        
      
        /**
         * Get all display languages
         */
        $allLangs = $objLang->getAll(array('sorting ASC'))->toArray();
        /**
         * Check permisison for each language
         */
        foreach ($allLangs as $index => $lang) {
            if (false == $this->checkPermission('new_product', null, $lang['lang_id'])) {
                /**
                 * Clear data
                 */
                unset($data[$lang['lang_id']]);
                /**
                 * Disappear this language
                 */
                unset($allLangs[$index]);
            }
        }
        
        $errors = array();
        if (false !== $data) {
            /**
             * Insert new product
             */
            $newProduct = $data;
            $newProduct['created_date'] = time();
            /**
             * Change format date
             */
            if (null == $newProduct['sale_off_start_date']) {
                unset($newProduct['sale_off_start_date']);
            } else {
                $tmp = explode('/', $newProduct['sale_off_start_date']);
                $newProduct['sale_off_start_date'] = mktime(0, 0, 0, $tmp[1], $tmp[0], $tmp[2]);
            }
            if (null == $newProduct['sale_off_end_date']) {
                unset($newProduct['sale_off_end_date']);
            } else {
                $tmp = explode('/', $newProduct['sale_off_end_date']);
                $newProduct['sale_off_end_date'] = mktime(0, 0, 0, $tmp[1], $tmp[0], $tmp[2]);
            }
            /**
             * Sorting
             */
            if (null == $newProduct['sorting']) {
                unset($newProduct['sorting']);
            }
            if (false == $this->checkPermission('new_product', null, '*')) {
                $newProduct['genabled']          = 0;
                $newProduct['sale_off_start_date']   = null;
                $newProduct['sale_off_end_date'] = null;
                $newProduct['sorting']           = 1;
            }
        
            /**
             * Slipt intro_text & full_text
             */
            foreach ($allLangs as $index => $lang) {
                 list($newProduct[$lang['lang_id']]['intro_text'], $newProduct[$lang['lang_id']]['full_text'])= Nine_Function::splitTextWithReadmore($newProduct[$lang['lang_id']]['full_text']);
            }
            /**
             * Remove empty images
             */
            if (is_array($newProduct['images'])) {
                foreach ($newProduct['images'] as $index => $image) {
                    if (null == $image) {
                        unset($newProduct['images'][$index]);
                    } else {
                        $newProduct['images'][$index] = Nine_Function::getImagePath($image);
                    }
                }
            }
            $newProduct['images'] = implode('||', $newProduct['images']);
            try {
                /**
                 * Increase all current sortings
                 */
                if (1 > $newProduct['sorting']) {
                    $newProduct['sorting'] = 1;
                }
                $objProduct->increaseSorting($newProduct['sorting'], 1);
                
                $objProduct->insert($newProduct);
                /**
                 * Message
                 */
                $this->session->productMessage =  array(
                           'success' => true,
                           'message' => Nine_Language::translate('Product is created successfully.')
                        );
//                echo " here";die;
 $this->_redirect('product/admin/manage-product');
            } catch (Exception $e) {
                $errors = array('main' => Nine_Language::translate('Can not insert into database now'));
            }
        } else {
            $data = array('sorting' => 1);
        }
        /**
         * Prepare for template
         */
        $this->view->allCats = $allCats;
        $this->view->allLangs = $allLangs;
        $this->view->errors = $errors;
        $this->view->datepickerFormat = Nine_Registry::getConfig('datepickerFormat');
        $this->view->data = $data;
        $this->view->headTitle(Nine_Language::translate('New Product'));
        $this->view->menu = array('product', 'newproduct');
        $this->view->fullPermisison = $this->checkPermission('new_product', null, '*'); 
    }
    

    
    public function editProductAction()
    {
        $objProduct = new Models_Product();
        $objCat     = new Models_ProductCategory();
        $objLang    = new Models_Lang();
        /**
         * Check permission
         */
        if (false == $this->checkPermission('edit_product', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $gid     = $this->_getParam('gid', false);
        $lid    = $this->_getParam('lid', false); 
        if (false == $gid) {
            $this->_redirect('product/admin/manage-product');
        }
        /**
         * Check permission
         */
        if ((false == $lid && false == $this->checkPermission('edit_product', null, '*'))
        ||  (false != $lid && false == $this->checkPermission('edit_product', null, $lid))) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $data   = $this->_getParam('data', false);
        
        /**
         * Get all categories
         */
        $allCats = $objCat->buildTree($objCat->getAll(array('sorting ASC'))->toArray());
        /**
         * Get all product languages
         */
        
        $allLangs = $objLang->getAll(array('sorting ASC'))->toArray();
        $allProductLangs = $objProduct->setAllLanguages(true)->getByColumns(array('product_gid=?' => $gid))->toArray();
        /**
         * Check permisison for each language
         */
        foreach ($allLangs as $lang) {
            if (false == $this->checkPermission('edit_product', null, $lang['lang_id'])) {
                /**
                 * Disappear this language
                 */
                unset($allLangs[$index]);
                unset($allProductLangs[$lang['lang_id']]);
                unset($data[$lang['lang_id']]);
            }
        }
        
        $errors = array();
        if (false !== $data) {
            /**
             * Insert new product
             */
            $newProduct = $data;
            /**
             * Change format date
             */
            if (null != $newProduct['sale_off_start_date']) {
                $tmp = explode('/', $newProduct['sale_off_start_date']);
                $newProduct['sale_off_start_date'] = mktime(0, 0, 0, $tmp[1], $tmp[0], $tmp[2]);
            }
            if (null != $newProduct['sale_off_end_date']) {
                $tmp = explode('/', $newProduct['sale_off_end_date']);
                $newProduct['sale_off_end_date'] = mktime(0, 0, 0, $tmp[1], $tmp[0], $tmp[2]);
            }
            /**
             * Sorting
             */
            if (null == $newProduct['sorting']) {
                unset($newProduct['sorting']);
            }
            if (false == $this->checkPermission('new_product', null, '*')) {
                unset($newProduct['genabled']);
                unset($newProduct['sale_off_start_date']);
                unset($newProduct['sale_off_end_date']);
                unset($newProduct['sorting']);
            }
        
            /**
             * Slipt intro_text & full_text
             */
            foreach ($allLangs as $index => $lang) {
                 list($newProduct[$lang['lang_id']]['intro_text'], $newProduct[$lang['lang_id']]['full_text'])= Nine_Function::splitTextWithReadmore($newProduct[$lang['lang_id']]['full_text']);
            }
            /**
             * Remove empty images
             */
            if (is_array($newProduct['images'])) {
                foreach ($newProduct['images'] as $index => $image) {
                    if (null == $image) {
                        unset($newProduct['images'][$index]);
                    } else {
                        $newProduct['images'][$index] = Nine_Function::getImagePath($image);
                    }
                }
            }
            $newProduct['images'] = implode('||', $newProduct['images']);
            try {
                /**                
                 * Update
                 */
                
                $objProduct->update($newProduct, array('product_gid=?' => $gid));
                /**
                 * Message
                 */
                $this->session->productMessage =  array(
                           'success' => true,
                           'message' => Nine_Language::translate('Product is updated successfully.')
                        );
                
                $this->_redirect('product/admin/manage-product');
            } catch (Exception $e) {
                $errors = array('main' => Nine_Language::translate('Can not insert into database now'));
            }
        } else {
            /**
             * Get old data
             */
            $data = @reset($allProductLangs);
            if (false == $data) {
                $this->session->productMessage = array(
                                               'success' => false,
                                               'message' => Nine_Language::translate("Product doesn't exist.")
                                           );
                $this->_redirect('product/admin/manage-product');
            }
            /**
             * Change date
             */
            if (0 != $data['sale_off_start_date']) {
                 $data['sale_off_start_date'] = date('d/m/Y', $data['sale_off_start_date']);
            } else {
                $data['sale_off_start_date'] = '';
            }
            if (0 != $data['sale_off_end_date']) {
                 $data['sale_off_end_date'] = date('d/m/Y', $data['sale_off_end_date']);
            } else {
                $data['sale_off_end_date'] = '';
            }
            /**
             * Format image
             */
            $data['images'] = explode('||', $data['images']);
            if (! is_array($data['images'])) {
                $data['images'] = array();
            }
            $data['images'] = array_pad($data['images'], 50, null);
            /**
             * Get all lang products
             */
            foreach ($allProductLangs as $product) {
                /**
                 * Rebuild readmore DIV
                 */
                $product['full_text'] = Nine_Function::combineTextWithReadmore($product['intro_text'], $product['full_text']);
                $data[$product['lang_id']] = $product;
            }
        }
//        echo "<pre>";print_r($data);die;
        /**
         * Prepare for template
         */
        $this->view->allCats = $allCats;
        $this->view->allLangs = $allLangs;
        $this->view->datepickerFormat = Nine_Registry::getConfig('datepickerFormat');
        $this->view->lid = $lid;
        $this->view->errors = $errors;
        $this->view->data = $data;
        $this->view->headTitle(Nine_Language::translate('Edit Product'));
        $this->view->menu = array('product','');
        $this->view->fullPermisison = $this->checkPermission('edit_product', null, '*');
    }

    public function enableProductAction()
    {
        $objProduct = new Models_Product();
        $gid = $this->_getParam('gid', false);
        $lid = $this->_getParam('lid', false);
        
        if (false == $gid) {
            $this->_redirect('product/admin/manage-product');
        }
        
        $gids = explode('_', trim($gid, '_'));
        if (false == $lid) {
            /**
             * Change general status
             * Check full permission
             */
            if (false == $this->checkPermission('edit_product', null, '*')) {
                $this->_forwardToNoPermissionPage();
                return;
            }
            try {
                foreach ($gids as $gid) {
                   $objProduct->update(array('genabled' => 1), array('product_gid=?' => $gid));
                }
                $this->session->productMessage = array(
                                                   'success' => true,
                                                   'message' => Nine_Language::translate('Product is enable successfully')
                                               );
            } catch (Exception $e) {
                $this->session->productMessage = array(
                                                   'success' => false,
                                                   'message' => Nine_Language::translate('Can NOT activate this product. Please try again')
                                               );
            }
        
        } else {
            /**
             * Check permission on each language
             */
            if (false == $this->checkPermission('edit_product', null, $lid)) {
                $this->_forwardToNoPermissionPage();
                return;
            }
            try {
                foreach ($gids as $gid) {
                   $objProduct->update(array('enabled' => 1), array('product_gid=?' => $gid, 'lang_id=?' => $lid));
                }
                $this->session->productMessage = array(
                                                   'success' => true,
                                                   'message' => Nine_Language::translate('Product is enable successfully')
                                               );
            } catch (Exception $e) {
                $this->session->productMessage = array(
                                                   'success' => false,
                                                   'message' => Nine_Language::translate('Can NOT activate this product. Please try again')
                                               );
            }
        }
        
        
        $this->_redirect('product/admin/manage-product');
    }

    
    public function disableProductAction()
    {
        $objProduct = new Models_Product();
        $gid = $this->_getParam('gid', false);
        $lid = $this->_getParam('lid', false);
        
        if (false == $gid) {
            $this->_redirect('product/admin/manage-product');
        }
        
        $gids = explode('_', trim($gid, '_'));
        if (false == $lid) {
            /**
             * Change general status
             * Check full permission
             */
            if (false == $this->checkPermission('edit_product', null, '*')) {
                $this->_forwardToNoPermissionPage();
                return;
            }
            try {
                foreach ($gids as $gid) {
                   $objProduct->update(array('genabled' => 0), array('product_gid=?' => $gid));
                }
                $this->session->productMessage = array(
                                                   'success' => true,
                                                   'message' => Nine_Language::translate('Product is disable successfully')
                                               );
            } catch (Exception $e) {
                $this->session->productMessage = array(
                                                   'success' => false,
                                                   'message' => Nine_Language::translate('Can NOT deactive this product. Please try again')
                                               );
            }
        
        } else {
            /**
             * Check permission on each language
             */
            if (false == $this->checkPermission('edit_product', null, $lid)) {
                $this->_forwardToNoPermissionPage();
                return;
            }
            try {
                foreach ($gids as $gid) {
                   $objProduct->update(array('enabled' => 0), array('product_gid=?' => $gid, 'lang_id=?' => $lid));
                }
                $this->session->productMessage = array(
                                                   'success' => true,
                                                   'message' => Nine_Language::translate('Product is disable successfully')
                                               );
            } catch (Exception $e) {
                $this->session->productMessage = array(
                                                   'success' => false,
                                                   'message' => Nine_Language::translate('Can NOT deactive this product. Please try again')
                                               );
            }
        }
        
        
        $this->_redirect('product/admin/manage-product');
    }
    
    public function deleteProductAction()
    {
        $objProduct = new Models_Product();
        $objCat = new Models_ProductCategory();
        /**
         * Check permission
         */
        if (false == $this->checkPermission('delete_product')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $gid = $this->_getParam('gid', false);
        
        if (false == $gid) {
            $this->_redirect('product/admin/manage-product');
        }
        
        $gids = explode('_', trim($gid, '_'));
        
        try {
            foreach ($gids as $gid) {
            	$product = @reset($objProduct->getByColumns(array('product_gid=?'=>$gid))->toArray());
            	$cat = @reset($objCat->getByColumns(array('product_category_gid=?'=>$product['product_category_gid']))->toArray());
            	if ( 0 == $cat['product_deleteable']){
            		$this->session->productMessage = array(
                                               'success' => false,
                                               'message' => Nine_Language::translate('Can NOT delete product ('. $gid .'). Please try again')
                                           );
                    $this->_redirect('content/admin/manage-product');
            	}
            	else {
            		 $objProduct->delete(array('product_gid=?' => $gid));
            	}
            }
            $this->session->productMessage = array(
                                               'success' => true,
                                               'message' => Nine_Language::translate('Product is deleted successfully')
                                           );
        } catch (Exception $e) {
            $this->session->productMessage = array(
                                               'success' => false,
                                               'message' => Nine_Language::translate('Can NOT delete this product. Please try again')
                                           );
        }
        $this->_redirect('product/admin/manage-product');
    }
    
    
    /**************************************************************************************************
     *                                         CATEGORY's FUNCTIONS
     **************************************************************************************************/
    public function manageCategoryAction()
    {
        $objLang    = new Models_Lang();
        $objCategory     = new Models_ProductCategory();
        
        /**
         * Check permission
         */
        if (false == $this->checkPermission('see_category', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $this->view->headTitle(Nine_Language::translate('manage Category '));
        $this->view->menu = array('product', 'manageproductcategory');
        
        
        $config = Nine_Registry::getConfig();
        $numRowPerPage = Nine_Registry::getConfig("defaultNumberRowPerPage");
        $currentPage = $this->_getParam("page",1);
        $displayNum = $this->_getParam('displayNum', false);
        
        /**
         * Update sorting
         */
        $data = $this->_getParam('data', array());
        foreach ($data as $id=>$value) {
            $value = intval($value);
            if (1 > $value) {
                continue;
            }
            $objCategory->update(array('sorting' => $value), array('product_category_id=?' => $id));
            $this->session->categoryMessage = array(
                                       'success' => true,
                                       'message' => Nine_Language::translate("Edit sort numbers successfully")
                                   );
        }
        
        /**
         * Get number of items per page
         */
        if (false === $displayNum) {
            $displayNum = $this->session->categoryDisplayNum;
        } else {
            $this->session->categoryDisplayNum = $displayNum;
        }
        if (null != $displayNum) {
            $numRowPerPage = $displayNum;
        }
        /**
         * Get condition
         */
        $condition = $this->_getParam('condition', false);
        if (false === $condition) {
            $condition = $this->session->categoryCondition;
        } else {
            $this->session->categoryCondition = $condition;
            $currentPage = 1;
        }
        if (false == $condition) {
            $condition = array();
        }
        
        /**
         * Get all display languages
         */
        $allLangs = $objLang->getAll(array('sorting ASC'))->toArray();
        /**
         * Check permisison for each language
         */
        foreach ($allLangs as $index => $lang) {
            if (false == $this->checkPermission('see_category', null, $lang['lang_id'])) {
                /**
                 * Disappear this language
                 */
                unset($allLangs[$index]);
            }
        }
        
        /**
         * Get all categorys
         */
        
        $allCategories  = $objCategory->setAllLanguages(true)->getAllCategories($condition, array('sorting ASC', 'product_category_gid DESC', 'product_category_id ASC'),
                                                   $numRowPerPage,
                                                   ($currentPage - 1) * $numRowPerPage
                                                  );
//        echo '<pre>';print_r($allCategories);die;
        /**
         * Count all categorys
         */
        $count = count($objCategory->setAllLanguages(true)->getallCategories($condition));
        /**
         * Format
         */
        $tmp    = array();
        $tmp2   = false;
        $tmpGid = @$allCategories[0]['product_category_gid'];
        foreach ($allCategories as $index=>$category) {
            /**
             * Change date
             */
            if (0 != $category['created_date']) {
                $category['created_date'] = date($config['dateFormat'], $category['created_date']);
            } else {
                $category['created_date'] = '';
            }
            if ($tmpGid != $category['product_category_gid']) {
                $tmp[]  = $tmp2;
                $tmp2   = false;
                $tmpGid = $category['product_category_gid'];
            }
            if (false === $tmp2) {
                $tmp2        = $category;
            }
            $tmp2['langs'][]  = $category;
            /**
             * Final element
             */
            if ($index == count($allCategories) - 1) {
                $tmp[] = $tmp2;
            }
        }
        $allCategories = $tmp;
//        echo '<pre>';print_r($allCategories);die;
        /**
         * Set values for tempalte
         */
        $this->setPagination($numRowPerPage, $currentPage, $count);
        $this->view->allCategories = $allCategories;
        $this->view->categoryMessage = $this->session->categoryMessage;
        $this->session->categoryMessage = null;
        $this->view->condition = $condition;
        $this->view->displayNum = $numRowPerPage;
        $this->view->fullPermisison = $this->checkPermission('see_category');
        $this->view->allLangs = $allLangs;
    }
    
    public function newCategoryAction()
    {
        $objLang = new Models_Lang();
        $objCategory = new Models_ProductCategory;
        /**
         * Check permission
         */
        if (false == $this->checkPermission('new_category', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $data = $this->_getParam('data', false);
        /**
         * Get all categories
         */
        $allCats = $objCategory->buildTree($objCategory->getAll(array('sorting ASC'))->toArray());
//        echo "<pre>";print_r($allCats);die; 
        
        /**
         * Get all templates
         */
        $allTemplates = Nine_Folder::getFolders(Nine_Registry::getViewPath().'templates');
//        echo "<pre>";print_r($allTemplates);die; 
        
        
        /**
         * Get all display languages
         */
        $allLangs = $objLang->getAll(array('sorting ASC'))->toArray();
        /**
         * Check permisison for each language
         */
        foreach ($allLangs as $index => $lang) {
            if (false == $this->checkPermission('new_category', null, $lang['lang_id'])) {
                /**
                 * Clear data
                 */
                unset($data[$lang['lang_id']]);
                /**
                 * Disappear this language
                 */
                unset($allLangs[$index]);
            }
        }
        
        $errors = array();
        if (false !== $data) {
            /**
             * Insert new category
             */
            $newCategory = $data;
            $newCategory['created_date'] = time();
            /**
             * Sorting
             */
            if (null == $newCategory['sorting']) {
                unset($newCategory['sorting']);
            }
            if (false == $this->checkPermission('new_category', null, '*')) {
                $newCategory['genabled']          = 0;
                $newCategory['sorting']           = 1;
            }
        
            /**
             * Remove empty images
             */
            if (is_array($newCategory['images'])) {
                foreach ($newCategory['images'] as $index => $image) {
                    if (null == $image) {
                        unset($newCategory['images'][$index]);
                    } else {
                        $newCategory['images'][$index] = Nine_Function::getImagePath($image);
                    }
                }
            }
            $newCategory['images'] = implode('||', $newCategory['images']);
            try {
                /**
                 * Increase all current sortings
                 */
                if (1 > @$newCategory['sorting']) {
                    $newCategory['sorting'] = 1;
                }
                if (null == $newCategory['parent_id']) {
                	$newCategory['parent_id'] = NULL;
                }
                $objCategory->increaseSorting($newCategory['sorting'], 1);

                $gid = $objCategory->insert($newCategory);
                
                /**
                 * Update id string
                 */
                $objCategory->update(array('gid_string'	=>	$gid), array('product_category_gid = ?' => $gid));
                $category = @reset($objCategory->getByColumns(array('product_category_gid = ?' => $gid))->toArray());
                $objCategory->updateGidString($category['parent_id'], $category['gid_string']);
                /**
                 * Message
                 */
                $this->session->categoryMessage =  array(
                           'success' => true,
                           'message' => Nine_Language::translate('Category is created successfully.')
                        );
                
                $this->_redirect('product/admin/manage-category');
            } catch (Exception $e) {
                $errors = array('main' => Nine_Language::translate('Can not insert into database now'));
            }
        } else {
            $data = array('sorting' => 1);
        }
        /**
         * Prepare for template
         */
        $this->view->allCats = $allCats;
        $this->view->allTemplates = $allTemplates;
        $this->view->allLangs = $allLangs;
        $this->view->errors = $errors;
        $this->view->datepickerFormat = Nine_Registry::getConfig('datepickerFormat');
        $this->view->data = $data;
        $this->view->headTitle(Nine_Language::translate('New Category'));
        $this->view->menu = array('product', 'newproductcategory');
        $this->view->fullPermisison = $this->checkPermission('new_category', null, '*'); 
    }
    

    
    public function editCategoryAction()
    {
        $objCategory     = new Models_ProductCategory();
        $objLang    = new Models_Lang();
        /**
         * Check permission
         */
        if (false == $this->checkPermission('edit_category', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $gid     = $this->_getParam('gid', false);
        $lid    = $this->_getParam('lid', false); 
        if (false == $gid) {
            $this->_redirect('product/admin/manage-category');
        }
        /**
         * Check permission
         */
        if ((false == $lid && false == $this->checkPermission('edit_category', null, '*'))
        ||  (false != $lid && false == $this->checkPermission('edit_category', null, $lid))) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $data   = $this->_getParam('data', false);
        
        /**
         * Get all categories
         */
        $allCats = $objCategory->buildTree($objCategory->getAll(array('sorting ASC'))->toArray());
        
        /**
         * Get all templates
         */
        $allTemplates = Nine_Folder::getFolders(Nine_Registry::getViewPath().'templates');
        
        /**
         * Get all category languages
         */
        
        $allLangs = $objLang->getAll(array('sorting ASC'))->toArray();
        $allCategoryLangs = $objCategory->setAllLanguages(true)->getByColumns(array('product_category_gid=?' => $gid))->toArray();
//        echo "<pre>";print_r($allCategoryLangs);die; 
        /**
         * Check permisison for each language
         */
        foreach ($allLangs as $index=>$lang) {
            if (false == $this->checkPermission('edit_category', null, $lang['lang_id'])) {
                /**
                 * Disappear this language
                 */
                unset($allLangs[$index]);
                unset($allCategoryLangs[$lang['lang_id']]);
                unset($data[$lang['lang_id']]);
            }
        }
        
        $errors = array();
        if (false !== $data) {
            /**
             * Insert new category
             */
            $newCategory = $data;
            /**
             * Sorting
             */
            if (null == $newCategory['sorting']) {
                unset($newCategory['sorting']);
            }
            if (false == $this->checkPermission('edit_category', null, '*')) {
                unset($newCategory['genabled']);
                unset($newCategory['sorting']);
            }
        
            /**
             * Remove empty images
             */
            if (is_array($newCategory['images'])) {
                foreach ($newCategory['images'] as $index => $image) {
                    if (null == $image) {
                        unset($newCategory['images'][$index]);
                    } else {
                        $newCategory['images'][$index] = Nine_Function::getImagePath($image);
                    }
                }
            }
            
            $newCategory['images'] = implode('||', $newCategory['images']);
            try {
                /**                
                 * Update
                 */
              	if (null == $newCategory['parent_id']) {
              	    $newCategory['parent_id'] = null;
                }
                /**
                 * Delete gid in parent
                 */
                $oldCategory = @reset($allCategoryLangs);
//                echo "<pre>";print_r($oldCategory);die; 
                /**
                 * @TODO fix bug here
                 */
                if ($oldCategory['parent_id'] != $newCategory['parent_id']) {
                    $objCategory->deleteGidString($oldCategory['parent_id'], $oldCategory['gid_string']);
                }
                /**
                 * Update new data
                 */
//                echo "<pre>";print_r($newCategory);die; 
                
                $objCategory->update($newCategory, array('product_category_gid=?' => $gid));
                
                /**
                 * Update new id string
                 */
                $category = @reset($objCategory->getByColumns(array('product_category_gid = ?' => $gid))->toArray());
                $objCategory->updateGidString($category['parent_id'], $category['gid_string']);
                
                /**
                 * Message
                 */
                $this->session->categoryMessage =  array(
                           'success' => true,
                           'message' => Nine_Language::translate('Category is updated successfully.')
                        );
                
                $this->_redirect('product/admin/manage-category');
            } catch (Exception $e) {
                $errors = array('main' => Nine_Language::translate('Can not insert into database now'));
            }
        } else {
            /**
             * Get old data
             */
            $data = @reset($allCategoryLangs);
            if (false == $data) {
                $this->session->categoryMessage = array(
                                               'success' => false,
                                               'message' => Nine_Language::translate("Category doesn't exist.")
                                           );
                $this->_redirect('product/admin/manage-category');
            }
            /**
             * Format image
             */
            $data['images'] = explode('||', $data['images']);
            if (! is_array($data['images'])) {
                $data['images'] = array();
            }
            $data['images'] = array_pad($data['images'], 50, null);
            /**
             * Get all lang categorys
             */
            foreach ($allCategoryLangs as $category) {
                $data[$category['lang_id']] = $category;
            }
            /**
             * Get all child category
             */
            $allChildCats = explode(',',trim($data['gid_string'],','));
            unset($allChildCats[0]);
           	foreach($allCats as $key =>	$item) {
           		if (false != in_array($item, $allChildCats)) {
           			unset($allCats[$key]);
           		}
           	}
        }
        /**
         * Remove it and its childs from category list
         */
        $oldData = @reset($allCategoryLangs);
        foreach ($allCats as $index => $item) {
            if (false !== strpos(",{$oldData['gid_string']},", ",{$item['product_category_gid']},")) {
                unset($allCats[$index]);
            }
        }
        /**
         * Prepare for template
         */
        $this->view->allCats = $allCats;
        $this->view->allTemplates = $allTemplates;
        $this->view->allLangs = $allLangs;
        $this->view->datepickerFormat = Nine_Registry::getConfig('datepickerFormat');
        $this->view->lid = $lid;
        $this->view->errors = $errors;
        $this->view->data = $data;
        $this->view->headTitle(Nine_Language::translate('Edit Category'));
        $this->view->menu = array('product','');
        $this->view->fullPermisison = $this->checkPermission('edit_category', null, '*');
    }

    public function enableCategoryAction()
    {
        $objCategory = new Models_ProductCategory;
        $gid = $this->_getParam('gid', false);
        $lid = $this->_getParam('lid', false);
        
        if (false == $gid) {
            $this->_redirect('product/admin/manage-category');
        }
        
        $gids = explode('_', trim($gid, '_'));
        if (false == $lid) {
            /**
             * Change general status
             * Check full permission
             */
            if (false == $this->checkPermission('edit_category', null, '*')) {
                $this->_forwardToNoPermissionPage();
                return;
            }
            try {
                foreach ($gids as $gid) {
                   $objCategory->update(array('genabled' => 1), array('product_category_gid=?' => $gid));
                }
                $this->session->categoryMessage = array(
                                                   'success' => true,
                                                   'message' => Nine_Language::translate('Category is enable successfully')
                                               );
            } catch (Exception $e) {
                $this->session->categoryMessage = array(
                                                   'success' => false,
                                                   'message' => Nine_Language::translate('Can NOT activate this category. Please try again')
                                               );
            }
        
        } else {
            /**
             * Check permission on each language
             */
            if (false == $this->checkPermission('edit_category', null, $lid)) {
                $this->_forwardToNoPermissionPage();
                return;
            }
            try {
                foreach ($gids as $gid) {
                   $objCategory->update(array('enabled' => 1), array('product_category_gid=?' => $gid, 'lang_id=?' => $lid));
                }
                $this->session->categoryMessage = array(
                                                   'success' => true,
                                                   'message' => Nine_Language::translate('Category is enable successfully')
                                               );
            } catch (Exception $e) {
                $this->session->categoryMessage = array(
                                                   'success' => false,
                                                   'message' => Nine_Language::translate('Can NOT activate this category. Please try again')
                                               );
            }
        }
        
        
        $this->_redirect('product/admin/manage-category');
    }

    
    public function disableCategoryAction()
    {
        $objCategory = new Models_ProductCategory;
        $gid = $this->_getParam('gid', false);
        $lid = $this->_getParam('lid', false);
        
        if (false == $gid) {
            $this->_redirect('product/admin/manage-category');
        }
        
        $gids = explode('_', trim($gid, '_'));
        if (false == $lid) {
            /**
             * Change general status
             * Check full permission
             */
            if (false == $this->checkPermission('edit_category', null, '*')) {
                $this->_forwardToNoPermissionPage();
                return;
            }
            try {
                foreach ($gids as $gid) {
                   $objCategory->update(array('genabled' => 0), array('product_category_gid=?' => $gid));
                }
                $this->session->categoryMessage = array(
                                                   'success' => true,
                                                   'message' => Nine_Language::translate('Category is disable successfully')
                                               );
            } catch (Exception $e) {
                $this->session->categoryMessage = array(
                                                   'success' => false,
                                                   'message' => Nine_Language::translate('Can NOT deactive this category. Please try again')
                                               );
            }
        
        } else {
            /**
             * Check permission on each language
             */
            if (false == $this->checkPermission('edit_category', null, $lid)) {
                $this->_forwardToNoPermissionPage();
                return;
            }
            try {
                foreach ($gids as $gid) {
                   $objCategory->update(array('enabled' => 0), array('product_category_gid=?' => $gid, 'lang_id=?' => $lid));
                }
                $this->session->categoryMessage = array(
                                                   'success' => true,
                                                   'message' => Nine_Language::translate('Category is disable successfully')
                                               );
            } catch (Exception $e) {
                $this->session->categoryMessage = array(
                                                   'success' => false,
                                                   'message' => Nine_Language::translate('Can NOT deactive this category. Please try again')
                                               );
            }
        }
        
        
        $this->_redirect('product/admin/manage-category');
    }
    
    public function deleteCategoryAction()
    {
        $objCategory = new Models_ProductCategory;
        /**
         * Check permission
         */
        if (false == $this->checkPermission('delete_category')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
        
        $gid = $this->_getParam('gid', false);
        
        if (false == $gid) {
            $this->_redirect('product/admin/manage-category');
        }
        
        $gids = explode('_', trim($gid, '_'));
        
        try {
            foreach ($gids as $gid) {
            	
            	$cat = @reset($objCategory->getByColumns(array('product_category_gid=?'=>$gid))->toArray());
            	if ( 0 == $cat['product_deleteable']){
            		$this->session->categoryMessage = array(
                                               'success' => false,
                                               'message' => Nine_Language::translate('Can NOT delete category ('. $gid .'). Please try again')
                                           );
                    $this->_redirect('content/admin/manage-category');
            	}
            	else {
            		 $objCategory->delete(array('product_category_gid=?' => $gid));
            	}
            }
            $this->session->categoryMessage = array(
                                               'success' => true,
                                               'message' => Nine_Language::translate('Category is deleted successfully')
                                           );
        } catch (Exception $e) {
            $this->session->categoryMessage = array(
                                               'success' => false,
                                               'message' => Nine_Language::translate('Can NOT delete this category. Please try again')
                                           );
        }
        $this->_redirect('product/admin/manage-category');
    }
}